import { List, Spin, Tag, Popconfirm } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import Search from 'antd/lib/input/Search';
import Text from 'antd/lib/typography/Paragraph';
import { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroller';
import { delArticle, searchOwner } from '../../services/api';
import { IUser } from '../../types';
import { Link, useHistory } from 'react-router-dom';
import { getTagColor } from '../../func';
import moment from 'moment';
import style from './style.module.less'

interface Item {
    _id: string,
    author: IUser,
    content: string,
    ctime: number,
    preview: number,
    status: number,
    tags: string,
    title: string
}

export default function MyArticle() {
    let history = useHistory()
    const [data, setData] = useState<Item[]>([])
    const [total, setTotal] = useState(0)
    const [pageIndex, setPageIndex] = useState(1)
    const [sort, setSort] = useState('ctime')
    const [keyword, setKeyword] = useState('')
    const [loading, setLoading] = useState(false)
    const [hasMore, setHasMore] = useState(true)

    useEffect(() => {
        searchOwner({
            pageIndex: 1,
            pageSize: 10,
            keyword: keyword,
            sort: sort
        }).then((res) => {
            if (res.data) {
                setData(res.data?.items)
                setTotal(res.data?.total)
            }
        })
    }, [keyword, sort])

    const handleInfiniteOnLoad = () => {
        setLoading(true)
        if (data.length >= total) {
            setLoading(false);
            setHasMore(false)
            return;
        }
        searchOwner({
            pageIndex: pageIndex + 1,
            pageSize: 10,
            keyword: keyword,
            sort: sort
        }).then((res) => {
            if (res.data?.items)
                setData(data.concat(res.data?.items))
            setPageIndex(pageIndex + 1)
            setLoading(false)
        })
    };

    return (
        <div className={style.warp}>
            <div className={style.header}>
                <div>我的创作 <span style={{color:'#ccc'}}>{total}</span></div>
                <div className={style.search}> 排序：
                    <a onClick={() => setSort('ctime')} className={sort === 'ctime' ? 'blue' : 'black'}>时间 </a>
                    <a onClick={() => setSort('preview')} className={sort === 'preview' ? 'blue' : 'black'}> 浏览量</a>
                    <Search placeholder="搜索文章" style={{ width: 200, marginLeft: 8 }} onSearch={(value) => setKeyword(value)} />
                </div>
            </div>
            <div className="demo-infinite-container">
                <InfiniteScroll
                    initialLoad={false}
                    pageStart={0}
                    loadMore={handleInfiniteOnLoad}
                    hasMore={!loading && hasMore}
                    useWindow={false}
                >
                    <List
                        rowKey='_id'
                        dataSource={data}
                        renderItem={item => (
                            <List.Item
                                key={item._id}
                                actions={[
                                    <a key="list-loadmore-edit" onClick={() => { history.push(`/Person/Edit/${item._id}`) }}>编辑</a>,
                                    <a key="list-loadmore-more" onClick={() => { history.push(`/Person/View/${item._id}`) }}>查看</a>,
                                    <Popconfirm
                                        placement="topRight"
                                        title="确定要删除吗？"
                                        onConfirm={() => { delArticle(item._id); window.location.reload(); }}
                                        okText="确定"
                                        cancelText="取消"
                                    ><a key="list-loadmore-delete">删除</a>
                                    </Popconfirm>
                                ]}>
                                <List.Item.Meta
                                    avatar={
                                        <>
                                        </>
                                    }
                                    title={<Link to={`/View/${item._id}`}><b>{item.title}</b> </Link>}
                                    description={<><Text style={{ width: '90%' }} ellipsis={true}>{item.content}</Text><div>{moment(item.ctime).format("YYYY-MM-DD HH:mm:ss")}</div></>}
                                />
                                <div>
                                    {item.tags.split(',').map((tag) => {
                                        return (<Tag color={getTagColor(tag)} key={tag}>{tag}</Tag>)
                                    })}
                                </div>
                                <div>
                                    <EyeOutlined style={{ marginRight: 5 }} />
                                    <span>{item.preview}</span>
                                </div>
                            </List.Item>
                        )}
                    >
                        {loading && hasMore && (
                            <div className="demo-loading-container">
                                <Spin />
                            </div>
                        )}
                    </List>
                </InfiniteScroll>
            </div>
        </div>
    );
}